package com.atguigu.gulimallcart.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimallcart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author houChen
 * @date 2022/1/5 22:24
 * @Description:
 *
 *   在执行目标方法之前，判断用户登录状态，并封装传递给controller请求
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * @Description:  目标方法执行之前进行拦截
     * @param
     * @author  houChen
     * @date  2022/1/5 22:30
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRespVo member =  (MemberRespVo)session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(member!=null){
            userInfo.setUserId(member.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if(CartConstant.TEMP_USER_COOKIE.equals(cookie.getName())){
                    userInfo.setUserKey(cookie.getValue());
                    userInfo.setTempUser(true);
                }
            }
        }
        //如果没有临时用户，那么一定分配一个临时用户
        if(StringUtils.isBlank(userInfo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfo.setUserKey(uuid);
        }
        threadLocal.set(userInfo);
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.getTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE,userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            //一个月cookie过期
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);
        }
    }
}